<template>
  <div class="crud_from_gadget_template"
       style="width:100%;height:100%"
       :id="id">
    <Portal to="right-disable"
            style="width:100%;height:100%;"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  style="width:100%;height: 100%;border:0">
        <el-card shadow="never"
                 class="aui-card--fill"
                 :style="isHasData?'width:100%;height: 100%;border:0;overflow: visible;':'width:100%;height: 100%;border:0;overflow: hidden;'">
          <div style="width:100%;height:100%;overflow: hidden;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName&& widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <div>
                <MoreMenu :slicer='slicer'
                          :fitToHeight='fitToHeight'
                          :gadgetId='id'
                          :gadgetType='gadgetInfo.com'
                          @updateQuery="query"
                          :widgetName="widgetName"
                          :businessType="gadgetInfo.businessType"
                          :id="gadgetInfo.id"
                          @showQueryModel="showQueryModel"
                          @fullScreen="fullScreen" />
              </div>
            </div>
            <div style="padding: 10px 10px;">
              <el-button type="primary"
                         size="small"
                         icon="el-icon-plus"
                         @click="openDialog()">{{ $t('new') }}</el-button>
              <el-button
                        v-if="gadgetSetting.showDeleteButton"
                         size="small"
                         @click="deleteFormMultiple">{{ $t('delete') }}</el-button>

              <el-input
                  v-if="isHasData && gadgetSetting.showSearch"
                  style="width: 200px; float: right"
                  prefix-icon="el-icon-search"
                  placeholder="search"
                  v-model="search">
              </el-input>
            </div>
            <div class="control-section"
                 style="margin: 0px 10px 10px 10px;height: calc(100% - 90px)">
              <div class="content-wrapper"
                   style="width:100%;height:100%;"
                   :class="gadgetSetting.report.allowGrouping?'':'showToobar'">
                <BTable :tableData="searchTableData(comDataList)"
                        :columns="comColumns"
                        :header-row-style="{height:'36px'}"
                        :header-cell-style="{height:'36px',padding:0}"
                        :summary-method="getSummaries"
                        :show-summary="comIsShowSummary&&!autoFull"
                        :conditionFormat="conditionFormat"
                        :startIndex="startIndex"
                        :autoFull="autoFull"
                        :endIndex="endIndex"
                        :stripe="conditionFormat && conditionFormat.length > 0 ?false :true"
                        :gadgetHeight="gadgetHeight"
                        @handleTableExport="handleTableExport"
                        @selection-change="handleSelectionChange"
                        @cell-click="tableCellClick"
                        @sort-change="sortChange"
                        :cell-class-name="tableCellClassName"
                        :gadgetSetting="gadgetSetting"
                        v-if="isHasData">
                  <el-table-column
                      slot="selection"
                      type="selection"
                      v-if="gadgetSetting.showSelection"
                      width="55">
                  </el-table-column>
                  <el-table-column
                    slot="index"
                    type="index"
                    width="50"
                    v-if="gadgetSetting.showLineNumbers"
                    ></el-table-column>
                  <el-table-column
                                   v-for="column in comColumns"
                                   :slot="column.field"
                                   :key="column.field"
                                   sortable
                                   :sort-method="(a,b) => customSort(a, b, column.field)"
                                   :align="getTextAlign(column.textAlign)"
                                   :prop="column.field"
                                   :min-width="(!column.maxWidth || column.maxWidth === 'auto') ? getColumnWidth(column.field) : column.maxWidth"
                                   :width="column.maxWidth">
                    <template slot="header">
                      <el-tooltip v-if="column.headerTextTooltip"
                                  effect="dark"
                                  :content="column.headerTextTooltip"
                                  placement="right">
                        <span style="white-space: nowrap;">
                          {{column.headerText?column.headerText:column.field}}
                        </span>
                      </el-tooltip>
                      <span style="white-space: nowrap;"
                            v-else>{{column.headerText?column.headerText:column.field}}</span>
                    </template>
                    <template slot-scope="scope">
                      <component :is="`${findTableTemplateName(column.templateName)}`"
                                :dataFrom="'Table'"
                                :curData="scope.row[column.field]"
                                :curRow="scope.row"
                                :rowHeight="gadgetSetting.report.rowHeight"
                                :textAlign="getTextAlign(column.textAlign,'flex')"
                                :column="column"></component>
                    </template>
                  </el-table-column>
                  <template slot="tableAction">
                    <el-table-column
                        fixed="right"
                        align="center"
                        min-width="200px"
                        :label="$t('custom.component.gadget.operations')">
                      <template slot-scope="scope">
                        <div style="display: flex;justify-content: center;">
                          <el-button size="mini" type="text" @click="commandClick('Edit',scope.row)">{{ $t('update') }}</el-button>
                          <el-button size="mini" type="text"  @click="commandClick('Delete',scope.row)" v-if="gadgetSetting.showDeleteButton">{{ $t('delete') }}</el-button>
                        </div>
                      </template>
                    </el-table-column>
                  </template>
                </BTable>
                <Pagination v-if="isHasData&&gadgetSetting.report.allowPaging" @query="query" v-model="pageConfig"></Pagination>
                <div v-if="!isHasData"
                     class="gadget-no-newdata">
                  <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"
                         :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
                </div>
              </div>
            </div>

          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting" />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
    <UserFormDialog :userformDialogData="userformDialogData"
                    @envent="query"
                    ref="userFormDialog"></UserFormDialog>
    <ExportOptionDialog :exportOptionDialogVisible="exportOptionDialogVisible"
          :loading="exportGetAllDataLoading"
          :pages="pageConfig.pages"
          v-if="pageFromType !== 'reportLayoutGrid'"
          @closeExportOptionDialog="closeExportOptionDialog"
          @confirmExport="confirmExport"></ExportOptionDialog>
    <export-dialog
        :visible.sync="exportDialog"
        :loading="exportGetAllDataLoading"
        :pages="pageConfig.pages"
        @confirm="gridExport"/>
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import {generalDateTimeFormat, generalDateFormat, generalBooleanFormat, isHaveQuotationMarks} from '@/utils/common'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import { defaultGadgetSettingList } from '@/utils/data-json'
import { grids } from 'ejs'
import JsPDF from 'jspdf'
import { getInnerText, getUrl } from '@/components/storybook/utilties/tools'
import UserFormDialog from '@/views/modules/mspbots/FormList/FormData/userFormDialog.vue'
import moment from 'moment'
import BTable from '@/components/storybook/b-table'
import {exportCvs, exportExcel, exportPdf} from "@/utils/exportPdfCvs";
import ExportOptionDialog from '@/components/export-option-dialog/dialog.vue'
import exportDialog from '@/components/export-option-dialog/export-dialog.vue'

Vue.prototype.$eventHub = new Vue()
export default {
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { UserFormDialog, BTable, Lastupdatetime, ExportOptionDialog, exportDialog, model: () => import('@/components/gadget/query-model/query-model') },
  data () {
    return {
      search: '',
      multipleSelection: [],
      sumObj: {},
      sumObjFixed: {},
      currentTime: null,
      floatNum: 0,
      maxColItem: 0,
      gadgetSetting: {},
      AggColumn: [],
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      dataList: [],
      loading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'crudformgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'crudformgadget' }).gadgetSetting
        }
      },
      conditionFormat: [],
      employeetemplate: function () {
        return {
          template: Vue.component('employeetemplate', {
            template: ` <el-tooltip class="item" effect="dark" :content="$data.data.headerTextTooltip" placement="top-start" v-if="$data.data.headerTextTooltip">
                          <div style="text-align:left">{{$data.data.headerText}}</div>
                        </el-tooltip>
                         <div v-else style="text-align:left">{{$data.data.headerText}}</div>
                        `
          })
        }
      },
      footerTemp: function () {
        return {
          template: Vue.component('footerTemplate', {
            template: `<span>{{data.Custom}}</span>`,
            data () { return { data: {} } }
          })
        }
      },
      AverageTemp: function () {
        return {
          template: Vue.component('footerTemplate', {
            template: `<span>{{data.Custom}}</span>`,
            data () { return { data: {} } }
          })
        }
      },
      Min: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Min}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      Max: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Max}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      Count: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Count}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      CrudBtn: function () {
        return { template: CrudBtn }
      },
      toolbarItem: [], // 'ExcelExport'
      wrapSettings: { wrapMode: 'Both' },
      queryId: '',
      queryDrillthrough: {},
      queryDrillthroughList: [],
      selectFields: [],
      widgetName: '',
      userformDialogData: {
        isNew: true,
        formTitle: null,
        formCode: null,
        id: null
      },
      formatDataList: [],
      linkedDatasetList: [],
      exportOptionDialogVisible: false,
      exportDialog: false,
      exportGetAllDataLoading: false,
      toolBarExportType: null
    }
  },

  created () {
    // this.query()
    Vue['this_crud_form_page_'] = this
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
    this.$eventHub.$on('commandClick', (type, row) => {
      this.commandClick(type, row)
    })
  },
  mounted () {
  },
  computed: {
    comDataList () {
      var _self = this
      // return Array.isArray(_self.dataList) ? _self.dataList : []
      var retdata = _self.dataList
      return retdata
    },
    comIsShowSummary () {
      return this.AggColumn.length !== 0
    },
    comColumns () {
      return this.gadgetSetting.report.columns.filter(v => v.visible)
    },
  },
  watch: {

  },
  methods: {
    getColumnWidth(columnName) {
      let maxLength = this.dataList.reduce((acc, row) => {
        const length = String(row[columnName]).length
        return length > acc ? length : acc
      }, 0)
      maxLength = columnName.length + 3 > maxLength ? columnName.length + 3 : maxLength
      return `${maxLength * 8 + 50}px` // 计算宽度
    },
    sortChange ({ prop, order }) {
      if (order) {
        this.dataList = this.dataList.sort((a, b) => {
          const aStr = a[prop] ? String(a[prop]).toLowerCase() : ''
          const bStr = b[prop] ? String(b[prop]).toLowerCase() : ''
          let compareValue = aStr.localeCompare(bStr)
          return order === 'ascending' ? compareValue : -compareValue
        })
      } else {
        this.dataList = this._.cloneDeep(this.dataListClone)
      }
    },
    customSort(a, b, filed) {
      const aStr = a[filed] ? a[filed].toLowerCase() : ''
      const bStr = b[filed] ? b[filed].toLowerCase() : ''
      return aStr.localeCompare(bStr)
    },
    searchTableData (val) {
      if (!Array.isArray(val)) return []
      return val.filter(data => {
        let str = ''
        Object.keys(data).map(item => {
          str = str + JSON.stringify(data[item])
        })
        return !this.search || str.toLowerCase().includes(this.search.toLowerCase())
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    commandClick (type, row) {
      var _self = this
      if (type === 'Edit') {
        const rowData = {
          formCode: _self.gadgetSetting.report.formList,
          id: row[_self.gadgetSetting.report.formData]
        }
        this.openDialog(rowData)
      }
      if (type === 'AddOrEdit') {
        const rowData = {
          formCode: _self.gadgetSetting.report.formList,
          id: row[_self.gadgetSetting.report.formData] ? row[_self.gadgetSetting.report.formData] : ''
        }
        this.openDialog(rowData, 1)
      }
      if (type === 'Delete') {
        this.deleteForm({ id: row[_self.gadgetSetting.report.formData] })
      }
    },
    openDialog (row,type) {
      if (row) {
        if (!row.formCode) {
          if (type && !row.id) {
            return this.$message.error('Please select formList and formData in config and click Apply')
          }
        }        
        this.userformDialogData = {
          isNew: false,
          formTitle: '', // this.$route.query.formTitle
          formCode: row.formCode,
          id: row.id ? row.id : ''
        }
      } else {
        if (!this.gadgetSetting.report.formList) return this.$message.error('Please select formList in config and click Apply')
        this.userformDialogData = { isNew: true, formCode: this.gadgetSetting.report.formList, formTitle: '' }
      }
      this.$nextTick(() => {
        if (this.$refs.userFormDialog) {
          this.$refs.userFormDialog.visible = true
        }
      })
    },
    deleteFormMultiple () {
      if (!this.multipleSelection.length) return false
      this.$confirm('Are you sure to delete?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(async () => {
        const { deleteFormMultiple } = this.$interface.reports
        const params = this.multipleSelection.map(item => {
          return item[this.gadgetSetting.report.formData]
        })
        await deleteFormMultiple(params)
        this.$message({
          type: 'success',
          message: 'Successfully deleted!'
        })
        this.query()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Deletion canceled'
        })
      })
    },
    deleteForm (row) {
      if (!this.gadgetSetting.report.formList || !row.id) return this.$message.error('Please select formList and formData in config and click Apply')
      this.$confirm('Are you sure to delete?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        const params = { id: row.id }
        this.$interface.reports.deleteFormDataApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            this.loading = false
            return this.$message.error(res.msg)
          }
          this.$message({
            type: 'success',
            message: 'Successfully deleted!'
          })
          this.query()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Deletion canceled'
        })
      })
    },
    sortComparer: function (reference, comparer) {
      if (reference === 0 && this.isNull(comparer)) {
        return 1
      }
      if (reference < comparer) {
        return -1
      }
      if (reference > comparer) {
        return 1
      }
      return 0
    },
    isNull (value) {
      if (!value && typeof value !== 'undefined' && value !== 0) {
        return true
      } else {
        return false
      }
    },
    customSumFn: function (data, col) {
      let countLength = 0
      let floatNum = 0
      let num = 0
      for (let index = 0; index < this.dataList.length; index++) {
        let item = this.dataList[index]
        let data = grids.getObject(col.field, item)
        if (!data) continue
        let numData = Number(data)
        countLength += numData
      }
      if (!Number.isInteger(countLength)) { num = countLength.toString().split('.')[1].length }
      if (num < 3) floatNum = num
      else floatNum = 2
      return this.toDecimal(countLength, floatNum)
    },
    toDecimal (x, m) {
      var val = Number(x)
      if (!isNaN(parseFloat(val))) {
        val = val.toFixed(m)
      }
      return val
    },
    customAggregateFn: function (data, col) {
      let count = grids.getObject('count', data)
      let Aggregate = 0
      for (let index = 0; index < this.dataList.length; index++) {
        let item = this.dataList[index]
        let data = grids.getObject(col.field, item)
        if (!data) continue
        let numData = Number(data)
        Aggregate += numData
      }
      let point = 2
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        let item = this.gadgetSetting.report.columns[index]
        if (col.field === item.field) {
          point = item.decimalPoint
          break
        }
      }
      // return Aggregate / count
      return this.fomatFloat(Aggregate / count, point)
    },
    fomatFloat (src, pos) {
      return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos)
    },
    returntempate (type) {
      if (type === 'Sum') {
        return this.Sum
      } else if (type === 'Average') {
        return this.Average
      } else if (type === 'Min') {
        return this.Min
      } else if (type === 'Max') {
        return this.Max
      } else if (type === 'Count') {
        return this.Count
      }
    },
    extractColumn () {
      this.maxColItem = 0
      let parentArr = []
      for (let i = 0; i < 5; i++) {
        let itemArr = []
        for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
          let item = this.gadgetSetting.report.columns[index]
          if (item.type === 'number' && item.aggregates.length > 0) {
            this.sumObj[item.field] = item.aggregates
            if (item.aggregates.includes('Average')) this.sumObjFixed[item.field] = item.decimalPoint
            if (this.maxColItem < item.aggregates.length) this.maxColItem = item.aggregates.length
            if (item.aggregates[i]) {
              itemArr.push({
                value: item.aggregates[i],
                field: item.field
              })
            }
          }
        }
        if (itemArr.length > 0) parentArr.push(itemArr)
      }
      this.AggColumn = parentArr
    },
    getJsx (val = {}) {
      let result = ""
      const keyArr = Object.keys(val)
      switch (keyArr.length) {
        case 1:
          result = (
              <div>
                <span>{keyArr[0]}:{val[keyArr[0]]}</span>
              </div>
          )
          break;
        case 2:
          result = (
              <div>
                <span>{keyArr[0]}:{val[keyArr[0]]}</span>
                <br />
                <span>{keyArr[1]}:{val[keyArr[1]]}</span>
              </div>
          )
          break;
        case 3:
          result = (
              <div>
                <span>{keyArr[0]}:{val[keyArr[0]]}</span>
                <br />
                <span>{keyArr[1]}:{val[keyArr[1]]}</span>
                <br />
                <span>{keyArr[2]}:{val[keyArr[2]]}</span>
              </div>
          )
          break;
        case 4:
          result = (
              <div>
                <span>{keyArr[0]}:{val[keyArr[0]]}</span>
                <br />
                <span>{keyArr[1]}:{val[keyArr[1]]}</span>
                <br />
                <span>{keyArr[2]}:{val[keyArr[2]]}</span>
                <br />
                <span>{keyArr[3]}:{val[keyArr[3]]}</span>
              </div>
          )
          break;
        case 5:
          result = (
              <div>
                <span>{keyArr[0]}:{val[keyArr[0]]}</span>
                <br />
                <span>{keyArr[1]}:{val[keyArr[1]]}</span>
                <br />
                <span>{keyArr[2]}:{val[keyArr[2]]}</span>
                <br />
                <span>{keyArr[3]}:{val[keyArr[3]]}</span>
                <br />
                <span>{keyArr[4]}:{val[keyArr[4]]}</span>
              </div>
          )
          break;

        default:
          break;
      }
      return result
    },
    rowDataBound (args) {
      args.row.childNodes.forEach(item => {
        if (item.dataset.bgc) {
          args.row.style.backgroundColor = item.dataset.bgc
        }
        if (item.dataset.color) {
          args.row.childNodes.forEach(ii => {
            if (!ii.style.color) {
              ii.style.color = item.dataset.color
            }
          })
        }
      })
    },
    customiseCell (args) {
      try {
        let conditionFormat = JSON.parse(JSON.stringify(this.conditionFormat))
        let arr = conditionFormat.map((item, index) => {
          let result = this.selectFields.find((col) => {
            return col.alias === item.dataForm.filters.rules[0].key
          })
          if (result) {
            item.dataForm.filters.rules[0].businessType = result.businessType
            item.dataForm.filters.rules[0].fieldsFormat = result.fieldsFormat
          }
          if (result && result.businessType) {
            switch (result.businessType) {
              case 'boolean':
                item.dataForm.filters.rules[0].value = generalBooleanFormat(item.dataForm.filters.rules[0].value, item.dataForm.filters.rules[0].fieldsFormat ? item.dataForm.filters.rules[0].fieldsFormat : 'True/False')
                break
              case 'date':
                item.dataForm.filters.rules[0].value = generalDateFormat(item.dataForm.filters.rules[0].value, item.dataForm.filters.rules[0].fieldsFormat ? item.dataForm.filters.rules[0].fieldsFormat : 'YYYY-MM-DD')
                break
              case 'datetime':
                item.dataForm.filters.rules[0].value = generalDateTimeFormat(item.dataForm.filters.rules[0].value, item.dataForm.filters.rules[0].fieldsFormat ? item.dataForm.filters.rules[0].fieldsFormat : 'YYYY-MM-DD HH:mm:ss')
                break
              default:
                item.dataForm.filters.rules[0].value = item.dataForm.filters.rules[0].value
                break
            }
          }
          return item
        })
        var column = args.column.field
        var res = arr.filter(item => {
          if (item.dataForm.filters.rules.length !== 0) {
            return item.dataForm.filters.rules[0].key === column
          }
        })

        if (args.data) {
          res.reverse().forEach(it => {
            if (it) {
              let str = ''
              it.dataForm.filters.rules.forEach(ii => {
                // eslint-disable-next-line
                var val = args.data[ii.key].toString()
                if (ii.type === 'date' || ii.type === 'datetime') {
                  val = moment(args.data[`date_or_datetime_type_copy_${ii.key}`].toString()).format('YYYY-MM-DD')
                  let dateRange = ii.valueList && Array.isArray(ii.valueList) ? ii.valueList : []
                  if (dateRange.length) {
                    let operator = it.dataForm.filters.condition === 'and' ? '&&' : '||'
                    if (dateRange.length === 1) {
                      if (dateRange[0].startTime === dateRange[0].endTime) {
                        str += (!str ? '' : operator) + `('${val}' ${ii.opt} '${dateRange[0].startTime}')`
                      } else {
                        if (ii.opt === '==') {
                          str += (!str ? '' : operator) + `('${val}' >= '${dateRange[0].startTime}' && '${val}' <= '${dateRange[0].endTime}')`
                        }
                        if (ii.opt === '!=') {
                          str += (!str ? '' : operator) + `('${val}' < '${dateRange[0].startTime}' || '${val}' > '${dateRange[0].endTime}')`
                        }
                        if (ii.opt === '>') {
                          str += (!str ? '' : operator) + `('${val}' > '${dateRange[0].endTime}')`
                        }
                        if (ii.opt === '>=') {
                          str += (!str ? '' : operator) + `!('${val}' < '${dateRange[0].startTime}')`
                        }
                        if (ii.opt === '<') {
                          str += (!str ? '' : operator) + `('${val}' < '${dateRange[0].startTime}')`
                        }
                        if (ii.opt === '<=') {
                          str += (!str ? '' : operator) + `!('${val}' > '${dateRange[0].endTime}')`
                        }
                      }
                    } else if (ii.opt === '==' || ii.opt === '!=') {
                      let result = ''
                      if (ii.opt === '==') {
                        dateRange.forEach(v => {
                          result += `('${val}' >= '${v.startTime}' && '${val}' <= '${v.endTime}')||`
                        })
                      } else {
                        dateRange.forEach(v => {
                          result += `('${val}' < '${v.startTime}' || '${val}' > '${v.endTime}')&&`
                        })
                      }
                      if (result.substr(-2) === '||' || result.substr(-2) === '&&') {
                        result = result.substr(0, result.length - 2)
                      }
                      str += (!str ? '' : operator) + result
                    } else if (ii.opt === '>') {
                      str += (!str ? '' : operator) + `('${val}' > '${dateRange[dateRange.length - 1].endTime}')`
                    } else if (ii.opt === '>=') {
                      str += (!str ? '' : operator) + `!('${val}' < '${dateRange[0].startTime}')`
                    } else if (ii.opt === '<') {
                      str += (!str ? '' : operator) + `('${val}' < '${dateRange[0].startTime}')`
                    } else if (ii.opt === '<=') {
                      str += (!str ? '' : operator) + `!('${val}' > '${dateRange[dateRange.length - 1].endTime}')`
                    }
                  }
                } else {
                  if (ii.opt === '==' || ii.opt === '!=') {
                    if (!str) {
                      str += `("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                    } else {
                      if (it.dataForm.filters.condition === 'and') {
                        str += `&& ("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                      } else {
                        str += `|| ("${(val).toString()}"   ${ii.opt}   "${(ii.value).toString()}")`
                      }
                    }
                  } else {
                    if (!str) {
                      str += (Number(val) + ii.opt + Number(ii.value))
                    } else {
                      if (it.dataForm.filters.condition === 'and') {
                        str += `&& (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                      } else {
                        str += `|| (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                      }
                    }
                  }
                }
              })
              // eslint-disable-next-line
              let res1 = eval(`${str}`)
              if (res1) {
                if (it.entireRow === 'row') {
                  args.cell.dataset.bgc = it.backgroundColor
                  args.cell.dataset.color = it.textColor
                } else {
                  args.cell.style.color = it.textColor ? it.textColor : '#000000'
                  args.cell.style.backgroundColor = it.backgroundColor
                }
              }
            }
          })
        }
      } catch (err) {

      }
    },
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        this.applyGadgetSetting()
      }
    },
    load (item) {
      this.grid = this.$refs.datagrid
      this.gadgetHeight = this.gadgetInfo.h * 20 - 15
    },
    applyGadgetSetting () {
      let columnsList = []
      let isAutofit = false
      // process link column
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        const element = this.gadgetSetting.report.columns[index]
        // add template and drillThrough
        columnsList.push(element.field)
        if (this.gadgetSetting.report.columns[0] && !this.gadgetSetting.report.columns[0].width) {
          isAutofit = true
        }
        // datetime format bugfix
        if (this.gadgetSetting.report.columns[index].type === 'datetime') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
        if (this.gadgetSetting.report.columns[index].type === 'date') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
      }
      // this.gadgetSetting.report.columns.push(this.CrudBtn)
      // this.gadgetSetting.report.columns.pop()
      if (isAutofit) {
        columnsList = Object.keys(this.dataList[0])
        this.grid.ej2Instances.autoFitColumns(columnsList)
      }
      // this.grid.ej2Instances.setProperties(this.gadgetSetting.report)
    },
    queryModelClosed () {
      this.$eventHub.$on('commandClick', (type, row) => {
        this.commandClick(type, row)
      })
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    queryModelPreview () {
      this.query()
    },
    showQueryModel () {
      this.$eventHub.$off('commandClick')
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = newH * 20 - this.heightoffset - 35 + 32
      this.gadgetWidth = newWPx
    },
    async query (e) {
      let isPaging = false
      try {
        if (this.isQueryModel && this.isQueryModel()) {
          isPaging = this.dataInfo.gadgetSetting.report.allowPaging
        } else {
          const { gadgetSetting } = await this.getWidgetInfo(this.id)
          isPaging = gadgetSetting.report.allowPaging
        }
      } catch (error) {

      }
      var _self = this
      // this.dataList = []
      if (e !== 'auto') {
        this.loading = true
        _self._.merge(_self.gadgetSetting, _self.queryModelDefaultSetting.dataInfo.gadgetSetting)
      }
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!param.pageId) {
        param.type = 'widget'
      }
      _self.queryDrillthrough = {}
      _self.queryDrillthroughList = []
      _self.selectFields = []
      this.isHasData = false
      if(this.$route.path !== '/publicReportPdf'&& isPaging) {
        param.current = this.pageConfig.current
        param.size = this.pageConfig.pageSize
      }
      this.$interface.reports.getReportDataInfo(param)
        .then(({ data: res }) => {
          _self.verifyHasData(res)
          try {
            _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
          } catch (error) {

          }
          _self.heightoffset = 5
          _self.gadgetHeight = (_self.gadgetInfo.h * 20) - _self.heightoffset - 15
          if (res.config) {
            _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
            _self.toolbarItem = _self.gadgetSetting.report.allowGrouping ? _self.gadgetSetting.report.toolbar : []
            _self.setfieldsFormat(res.selectFields)
          }
          if (res.name) {
            _self.widgetName = res.name
          } else if (this.wName) {
            _self.widgetName = this.wName
          } else {
            _self.widgetName = _self.gadgetSetting.headerTitle
          }
          _self.isGridInit = false
          // process data
          if (res.data) {
            try {
              if(res.data.records) {
                this.pageConfig.total = res.data.total
                res.data = res.data.records
              }
              this.formatDataList = this.formatData(JSON.parse(JSON.stringify(res.data)), res.selectFields, 'gridgadget')
            } catch (error) {
              
            }
            res.data = JSON.parse(JSON.stringify(res.data))
            _self.dataList = JSON.parse(JSON.stringify(res.data))
            _self.dataListClone = _self._.cloneDeep(_self.dataList)
            _self.setColumsFormat(res.selectFields)
            this.extractColumn()
            _self.conditionFormat = res.conditionFormat
            _self.linkedDatasetList = res.datasetSync
          }

          _self.isGridInit = false
          _self.selectFields = res.selectFields
        })
        .catch((error) => {
          if (this.wName) {
            this.widgetName = this.wName
          }
          this.isHasData = false
          this.loading = false
          if (error.response && error.response.status === 504) {
            this.errorStatus = '504'
            this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
          }
        }).finally(() => {
          this.currentTime = new Date()
          this.autoRefreshQuery(e)
          this.updateGadgetLoadingStatus(!this.loading)
        })
    },
    destroyed () {
      delete Vue['this_crud_form_page_']
    },
    remove () {
      this.close()
      if (this.drop.parentNode) {
        this.drop.parentNode.removeChild(this.drop)
      }
    },
    setfieldsFormat (fieldsList) {
      this.gadgetSetting.report.columns.forEach(item => {
        var res = fieldsList.find(i => {
          return i.bind === item.field
        })
        // if (!res) {
        //   res = fieldsList.find(e => e['dataType'] === 'dimension')
        // }
        // if (!res) {
        //   res = fieldsList.find(e => e['alias'] === 'dimension1')
        // }
        item.fieldsNewFormat = res && res.fieldsNewFormat
        item.fieldsFormat = res && res.fieldsFormat
        item.isNewPage = res && res.isNewPage
        item.showbymonday = res && res.showbymonday
        item.fieldsList = fieldsList
      })
    },
    setColumsFormat (fieldsList) {
      try {
        this.gadgetSetting.report.columns.forEach(item => {
          let fieldItemIndex = fieldsList.findIndex(e => e['bind'] === item['field'])
          // fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['dataType'] === 'dimension'))
          // fieldItemIndex === -1 && (fieldItemIndex = fieldsList.findIndex(e => e['alias'] === 'dimension1'))
          if (fieldItemIndex === -1) throw new Error('No Format')
          if (item.type === 'number' && fieldsList[fieldItemIndex].businessType === 'number') {
            item.templateName = 'formatNumber'
          } else {
            let templateName = this.findTemplateName(fieldsList[fieldItemIndex].fieldsFormat, fieldsList[fieldItemIndex].businessType)
            item.templateName = templateName
          }
        })
      } catch (error) { }
    },
    getSummaries (param) {
      let result = []
      const { columns } = param;
      if (!columns.length) return
      columns.forEach((column, index) => {
        const { property } = column;
        if (this.sumObj[property]) {
          const value = this.getResultValue(property, this.dataList, this.sumObj[property], this.sumObjFixed[property]);
          result[index] = this.getJsx(value);
        } else {
          result[index] = '';
        }
      })
      return result;
    },
    getResultValue (property, data, keyArr = [], Fixed = 0) {
      let resultObj = {}
      let sum = data.reduce((c, r) => Number(c) + Number(r[property]), 0)
      let count = data.length
      let min = Math.min(...data.map(v => v[property]))
      let max = Math.max(...data.map(v => v[property]))
      keyArr.forEach(v => {
        switch (v) {
          case 'Sum':
            resultObj.Sum = sum
            break;
          case 'Average':
            resultObj.Average = (sum / count).toFixed(Fixed)
            break;
          case 'Min':
            resultObj.Min = min
            break;
          case 'Max':
            resultObj.Max = max
            break;
          case 'Count':
            resultObj.Count = count
            break;

          default:
            break;
        }
      })
      return resultObj
    },
    handleTableExport (key) {
      if ((key === 'Excel Export' || key === 'CSV Export') && this.gadgetSetting.report.showExportOption) {
        this.toolBarExportType = key
        this.exportDialog = true
        return false;
      }
      switch (key) {
        case 'PDF Export':
          if (this.gadgetSetting.report.showExportOption) {
            this.exportOptionDialogVisible = true
          } else {
            exportPdf(this.formatDataList, this.selectFields)
          }
          break
        case 'Excel Export':
          this.formatDataList.forEach(item => {
            for (let key in item) {
              if (item[key] && item[key].toString().includes('<a')) {
                item[key] = item[key].replace(/[a-zA-z]+:\/\/[\S]*/, val => {
                  if (val[val.length - 1] === '"') {
                    val = val.slice(0, val.length - 1)
                  }
                  // eslint-disable-next-line
                  let temp = encodeURIComponent(val) + '\"'
                  return temp
                })
              }
            }
          })
          exportExcel(this.formatDataList, this.selectFields)
          break
        case 'CSV Export':
          exportCvs(this.formatDataList, this.selectFields)
          break
      }
    },
    closeExportOptionDialog () {
      this.exportOptionDialogVisible = false
    },
    async gridExport (exportType) {
      const data = await this.getGridAllData(exportType)
      switch (this.toolBarExportType) {
        case 'Excel Export':
          data.forEach(item => {
            for (const key in item) {
              if (item[key] && item[key].toString().includes('<a')) {
                item[key] = item[key].replace(/[a-zA-z]+:\/\/[\S]*/, val => {
                  if (val[val.length - 1] === '"') {
                    val = val.slice(0, val.length - 1)
                  }
                  return encodeURIComponent(val) + '\"'
                })
              }
            }
          })
          exportExcel(data, this.selectFields)
          break
        case 'CSV Export':
          exportCvs(data, this.selectFields)
          break
      }
      this.exportDialog = false
    },
    async confirmExport (options) {
      const data = await this.getGridAllData(options.exportData)
      exportPdf(data, this.selectFields, options)
      this.exportOptionDialogVisible = false
    },
    async getGridAllData (exportType) {
      const getAllData = exportType === 'All' && this.gadgetSetting.report.allowPaging
      if (exportType === 'Current') return this.formatDataList;
      this.exportGetAllDataLoading = true
      let obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (let key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      let param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!getAllData) {
        param.current = Number(exportType)
        param.size = this.pageConfig.pageSize
      }
      const getDataFunction = this.autoFull ? this.$interface.reports.getReportGridDataInfo : this.$interface.reports.getReportDataInfo
      const { data: { data: allData, selectFields } } = await getDataFunction(param)
      this.exportGetAllDataLoading = false
      return this.formatData(JSON.parse(JSON.stringify(param.current ? allData.records : allData)), selectFields, 'gridgadget')
    },
    tableCellClick (rowData, columnData) {
      for (var key in rowData) {
        if (rowData[key] && rowData[key].toString().includes("'") && (!rowData[key].toString().includes("''"))) {
          rowData[key] = rowData[key].toString().replace("'", "''")
        }
      }

      let column = this.selectFields.find(ele => ele.alias === columnData.label)
      if (this.selectFields.some(i => i.dataType === 'measure')) {
        if (!column.dataType) {
          return false
        }
      }
      if (!this.selectFields.some(i => i.dataType === 'dimension')) {
        if (!this.selectFields.some(i => i.dataType === 'measure')) {
          return false
        } else {
          this.queryId = this.selectFields.find(item => item.alias === columnData.label) ? this.selectFields.find(item => item.alias === columnData.label).queryId : ''
          return this.findOriginData('')
        }
      }
      if (column) {
        if (column.businessType === 'hyperlinks') {
          return false
        }
      }
      try {
        if (column.dataType === 'dimension') {
          return false
        }
      } catch (error) {

      }
      if (!rowData[columnData.label]) {
        return
      }

      var tempAlias = ''
      var tempData = ''
      var tempList = []
      var alias = ''
      var pointx = ''
      if (this.queryDrillthroughList && this.queryDrillthroughList.length > 0) {
        // eslint-disable-next-line no-debugger
        let dimensionList = this.selectFields.filter(e => e.dataType === 'dimension')
        dimensionList = this._.uniqBy(dimensionList, 'alias')
        let params = {}
        if (dimensionList.length > 1) {
          params.name = rowData[column.alias]
          params.seriesName = column.alias
          params.selectObj = rowData
          this.setDrillThroughInfoMoreDimension(params)
          return
        }
      } else {
        this.queryId = this.selectFields.find(item => item.alias === columnData.label) ? this.selectFields.find(item => item.alias === columnData.label).queryId : ''
        this.queryDrillthrough = this.selectFields.find(i => i.queryId === this.queryId)
        if (this.queryDrillthrough && this.queryDrillthrough.alias) {
          tempAlias = rowData[this.queryDrillthrough.alias]
          if (!tempAlias && tempAlias !== false && tempAlias !== 0 && tempAlias !== '') {
            alias = 'dimension1'
            if (rowData['dimension1']) {
              tempAlias = rowData['dimension1']
            }
          } else {
            alias = this.queryDrillthrough.alias
          }
          try {
            var fx1 = this.queryDrillthrough.fieldFx
          } catch (error) {

          }
          if (this.queryDrillthrough.dbType === 'datetime' && tempAlias) {
            tempData = this.dateTimeTypeDrillthroughGrid(this.queryDrillthrough, fx1 || this.queryDrillthrough.field, tempAlias)
          } else {
            if (this.queryDrillthrough.dbType === 'date' && tempAlias) {
              tempData = this.dateTypeDrillthroughGrid(this.queryDrillthrough, fx1 || this.queryDrillthrough.field, tempAlias)
            } else {
              pointx = rowData[alias]
              if (!pointx && pointx !== false && pointx !== 0 && pointx !== '') {
                pointx = ' is null'
              } else {
                let ifHaveQuotationMarks = typeof (pointx) !== 'boolean' ? isHaveQuotationMarks(pointx) : false
                pointx = ifHaveQuotationMarks ? '=' + pointx : "= '" + pointx + "'"
              }
              if (fx1) {
                tempData = (fx1 || '') + pointx
              } else {
                tempData = '"' + ((this.queryDrillthrough.field) ? (this.queryDrillthrough.field) : '') + '"' + pointx
              }
            }
          }
        }
      }

      if (tempList && tempList.length > 0) {
        for (let i = 0; i < tempList.length; i++) {
          if (i === tempList.length - 1) {
            tempData += tempList[i].item
          } else {
            tempData += tempList[i].item + ' and '
          }
        }
      }
      this.queryId = this.selectFields.find(item => item.alias === columnData.label) ? this.selectFields.find(item => item.alias === columnData.label).queryId : ''
      if (this.queryId) {
        let data = ''
        data = tempData
        this.findOriginData(data)
      }
    },
    tableCellClassName ({ row, column }) {
      try {
        if (this.isShowCursor) {
          if (column.label !== 'dimension1') {
            let res = this.selectFields.find(i => {
              return i.alias === column.label
            })
            if (res.dataType) {
              if (res.dataType !== 'dimension') {
                if (typeof row[column.label] === 'boolean') {
                  return 'cursor-pointer'
                } else if (Number(row[column.label]) !== 0) {
                  return 'cursor-pointer'
                }
              }
            }
          }
        }
      } catch (error) {

      }
    },
    getTextAlign (align = 'left', display = 'block') {
      if (display === 'flex') {
        return {
          'left': 'flex-start',
          'center': 'center',
          'right': 'flex-end'
        }[align.toLowerCase()]
      }
      return ['left', 'center', 'right'].includes(align.toLowerCase()) ? align.toLowerCase() : align
    },
  },
  destroyed () {
    this.$eventHub.$off('commandClick')
  }
}
const CrudBtn = Vue.component(
  'crud-btn', {
  template: `<div style="display: flex;justify-content: flex-end;">
      <el-button size="mini" plain type="success" @click="clickSelect('Edit',$data.data)">Edit</el-button>
      <el-button size="mini" plain type="danger"  @click="clickSelect('Delete',$data.data)">Delete</el-button>
    </div>`,
  data () {
    return {}
  },
  methods: {
    clickSelect (e, row) {
      this.$eventHub.$emit('commandClick', e, row)
    }
  }
}
)
</script>
<style lang="scss" scoped>
.content-wrapper {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 40%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}

::v-deep .e-dlg-content {
  max-height: 130px;
  overflow-y: auto;
}
.crud_from_gadget_template ::v-deep.e-grid .e-summarycell {
  font-size: 13px;
  background-color: #f6f6f6;
  border-color: #e0e0e0;
  color: rgba(0, 0, 0, 0.54);
  font-weight: normal;
}
.crud_from_gadget_template ::v-deep .showToobar .e-grid .e-toolbar {
  display: none;
}
.el-card ::v-deep .el-card__body {
  height: 100%;
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.e-grid ::v-deep .e-filter-popup {
  max-height: 300px !important;
  // overflow-y: auto;
  top: 80px !important;
}

.e-grid ::v-deep .e-checkboxlist {
  height: auto !important;
  overflow-y: visible !important;
}

::v-deep .e-grid {
  height: 100%;
  display: flex;
  flex-direction: column;
  .e-gridcontent {
    flex: 1;
    // height: calc(100% - 190px);
    .e-content {
      height: 100% !important;
      overflow: auto !important;
    }
  }
}
::v-deep .e-grid .e-ccdlg .e-cc-contentdiv {
  height: 106px;
  overflow-y: auto;
}
</style>
